//
//  HomeListController.m
//  QQplayground
//
//  Created by zhangxy on 2018/6/8.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "HomeListController.h"
#import "ZZHomeListCell.h"
#define cellIdentifier @"ZZHomeListCell"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "ZZHomeLabelView.h"
#import "ZZContentDetailController.h"
#import "ZZShareView.h"
#import "ZZContentCommentController.h"
#import "MyButton.h"
#import <MJRefresh.h>
#import "UIImage+ImageWithColor.h"
#import "LoginController.h"

#import "PictureBroswerTransitionAnimator.h"
#import "MWPhotoBrowser.h"


@interface HomeListController ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,ZZTopicCellDelegate,UIViewControllerTransitioningDelegate>{
    int page;
    // 最新、热门、推荐
    MyButton *checkMenuBtn;
    
    NavTypeEntity *checkLabel;
    
    // 选中的
    MyButton *checkBtn;
    
    UIView *startView;
}

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  NSArray *headerArr;
@property(nonatomic,strong)  UITableView *listTable;
@property(nonatomic,strong)  ZZHomeLabelView *labelView;
@property(nonatomic,strong)  UIView *headerView;
@property(nonatomic,strong)  UIView *headerViewLabels;
@property(nonatomic,strong)  UIButton *btnArrow;

@property(nonatomic,assign)CGRect   originFrame;
@property(nonatomic,strong)UIImageView   *avatarImageView;

@property (nonatomic, strong) PictureBroswerTransitionAnimator *animator;

@end

@implementation HomeListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    [self.view setBackgroundColor:UIColorFromRGB(BgSystemColor)];

//    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
//    [imgView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
//    [self.view addSubview:imgView];
    
    self.originFrame = CGRectMake(0, 0, ScreenWidth, 20);
    self.avatarImageView = [[UIImageView alloc] initWithFrame:self.originFrame];
    self.avatarImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.avatarImageView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    [self.view addSubview:self.avatarImageView];
    
    [self createTableView];
    self.listTable.estimatedRowHeight = 0;
    self.listTable.estimatedSectionHeaderHeight = 0;
    self.listTable.estimatedSectionFooterHeight = 0;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    
}

-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    
    [_listTable setBackgroundColor:UIColor.clearColor];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
    MJRefreshBackStateFooter *footer = [MJRefreshBackStateFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    _listTable.footer = footer;
    [self setTableSeparatorInset];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    _labelView = [[ZZHomeLabelView alloc] initWithTable:_listTable result:^(id tag, NSString *title) {
        checkLabel = tag;
        
        if(convertToString(checkLabel.tag_id).length == 0){
            [self getNavTagList:checkLabel];
        }
        
        [self loadBegin];
    }];
    _labelView.superVC = self;
    _listTable.tableHeaderView = _labelView;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    [header.arrowView setImage:[UIImage imageNamed:@"个人页点赞"]];
    header.activityIndicatorViewStyle  = UIActivityIndicatorViewStyleWhite;
    [header.stateLabel setTextColor:[UIColor whiteColor]];
    [header.lastUpdatedTimeLabel  setTextColor:[UIColor whiteColor]];
    [header setBackgroundColor:UIColorFromRGB(BgTitleColor)];
//    header.stateLabel.hidden=YES;
//    header.lastUpdatedTimeLabel.hidden=YES;
    _listTable.header = header;
    
    
    _headerView = [[UIView alloc] initWithFrame:CGRectZero];
    
    _headerViewLabels = [[UIView alloc] initWithFrame:CGRectZero];
    [_headerViewLabels setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
}


-(void)getNavTagList:(NavTypeEntity *) catEntity{
    
    [NetworkUtil POST:API_GetTagList parameters:@{@"cat_id":catEntity.cat_id,@"nav_id":convertToString(_entity.nav_id),@"size":@"20"} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"];
        if(arr.count > 0){
            _headerViewLabels.hidden = NO;
            [_headerViewLabels.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(22, 0, ScreenWidth-44, 44)];
            [label setText:@"标签"];
            [label setFont:FontThirteen];
            [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
            [_headerViewLabels addSubview:label];
            
            int i = 0;
            CGFloat sx = 7.0f;
            CGFloat y = 44;
            
            
            
            CGFloat x = 22;
            for (NSDictionary *item in arr) {
                NavTypeEntity *nav = [[NavTypeEntity alloc] initWithDictionary:item];
                CGRect f = CGRectMake(x, y, 30, 30);
                MyButton *btn = [self createMenuButton:f m:nav];
                [btn setTitle:nav.tag_name forState:0];
                CGSize s = [self autoWidthOfLabel:btn.titleLabel with:30];
                
                f.size.width = s.width + 30;
                if(CGRectGetMaxX(f) + 22 > ScreenWidth){
                    y = y + 30 + 10;
                    x = 22;
                }
                f.origin.x = x;
                f.origin.y = y;
                
                x = CGRectGetMaxX(f) + sx;
                
                btn.frame = f;
                [btn setTitleColor:UIColorFromRGB(TextWhiteColor) forState:UIControlStateSelected];
                [btn setTitleColor:UIColorFromRGB(Text6Color) forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageWithColor:UIColorFromRGB(BgTitleColor)] forState:UIControlStateSelected];
                [btn setBackgroundImage:[UIImage imageWithColor:UIColorFromRGBAlpha(BgSearchTitleColor,0.3)] forState:UIControlStateNormal];
                btn.layer.cornerRadius = 8.0f;
                btn.layer.masksToBounds = YES;
                [_headerViewLabels addSubview:btn];
                i = i + 1;
                
                if(checkBtn && [checkBtn.objTag isEqual:item]){
                    btn.selected = YES;
                }
            }
            
            
            _headerViewLabels.hidden = YES;
            [_headerViewLabels setFrame:CGRectMake(0, 44 , ScreenWidth, y + 44)];
            
            [self.headerView setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(self.headerViewLabels.frame))];
            [_listTable reloadData];
        }
    } failure:^(NSError *error, NSString *message) {
        
    }];
}

-(void)onItemClick:(MyButton *)btn{
    if(checkMenuBtn.tag == btn.tag){
        return;
    }
    checkMenuBtn.selected = NO;
    
    btn.selected = YES;
    checkMenuBtn = btn;
    
    
    [self loadBegin];
}


-(void)onItemLabelClick:(MyButton *) btn{
    NavTypeEntity *checkEntity = btn.objTag;
   
    if(checkBtn!=nil){
        checkBtn.selected = NO;
    }
    btn.selected = YES;
    checkBtn = btn;
    
    checkLabel = checkEntity;
    
    [self loadBegin];
}

-(void)btnArrowClick:(UIButton *) btn{
    if(_headerViewLabels.hidden){
        _headerViewLabels.hidden = NO;
        [_btnArrow setImage:[UIImage imageNamed:@"btn_arrow_up"] forState:0];
        [_listTable reloadData];
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//        [_listTable reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        [_btnArrow setImage:[UIImage imageNamed:@"btn_arrow_down"] forState:0];
        _headerViewLabels.hidden = YES;
        [_listTable reloadData];
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//        [_listTable reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}


-(void)setEntity:(NavTypeEntity *)entity{
    _entity = entity;
    
    if(![_entity.nav_name isEqual:@"推荐"] && ![_entity.nav_name isEqual:@"关注"]){
        [_headerView setFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        [_headerView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
        [self addBottomItems:_headerView];
        
        NavTypeEntity *nav = [NavTypeEntity new];
        nav.cat_id = @"0";
        [self getNavTagList:nav];
    }
    
    if(_labelView){
        [_labelView setEntiy:entity];
    }
    
    [NetworkUtil POST:API_GetNavList parameters:@{@"nav_id":_entity.nav_id} success:^(id responseObject, NSDictionary *dict) {
        if([self->_entity.nav_name isEqual:@"推荐"]){
            
            self->_labelView.backgroundColor = UIColor.whiteColor;
        }else{
            
            self->_labelView.backgroundColor = UIColorFromRGB(BgTitleColor);
        }
    } failure:^(NSError *error, NSString *message) {
        
    }];
    
    [self loadBegin];
}

-(void)loadBegin{
    page = 1;
    [self loadMoreData];
}

/**
 加载更多
 */
-(void)loadMoreData{
//    NSDictionary *p = @{@"user_id":convertIntToString((int)[UserUtil getUser].user_id),//@"2666684",
//                        @"nav_type":convertToString(_entity.nav_type),                                    // @"all",
//                        @"page":convertIntToString(page),
//                        @"page_size":@"20"
//                        };
    
    NSString *sort_type = @"recommend";
    if(checkMenuBtn){
        sort_type =((NavTypeEntity *)checkMenuBtn.objTag).nav_type;
    }
    
    NSString *cat_id = @"0";
    NSString *tag_id = @"0";
    if(checkLabel){
        if(convertToString(checkLabel.cat_id).length > 0){
            cat_id = checkLabel.cat_id;
        }
        if(convertToString(checkLabel.tag_id).length > 0){
            tag_id = checkLabel.tag_id;
        }
    }
    NSDictionary *p = @{@"sort_type":sort_type,
                        @"cat_id":cat_id,
                        @"tag_id":tag_id,
                        @"have_comment":@"1",
                        @"page":convertIntToString(page)
                        };
    NSString *api = API_GetHomeList(_entity.nav_type);
    if([@"skin" isEqual:_entity.nav_type]){
        api = API_GetHomeList(@"skins");
    }
    if([_entity.nav_type isEqual:@"gz"]){
        api = API_GetHomeFollowcontentlist;
        p = @{@"have_comment":@"1",
              @"session_uid":convertToString([UserUtil getUser].user_id),
              @"page":convertIntToString(page)};
    }else if([_entity.nav_type isEqual:@"tj"]){
        api = API_GetHomeRecommentlist;
        p = @{@"session_uid":convertToString([UserUtil getUser].user_id),
              @"page":convertIntToString(page)};
    }
    
    DLog(@"---type:%@", _entity.nav_type);
    DLog(@"---api:%@", api);
    DLog(@"---p:%@", p);
    
    [NetworkUtil POST:api parameters:p success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        if(page == 1){
            [self.listArray removeAllObjects];
        }
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            if([item isKindOfClass:[NSDictionary class]]){
                
            ZZHomeTopicEntity *model = [[ZZHomeTopicEntity alloc] initWithDictionary:item];
            if(![_entity.nav_type isEqual:@"gz"] && ![_entity.nav_type isEqual:@"tj"]){
                model.nav_type = _entity.nav_type;
                model.nav_name = _entity.nav_name;
            }
                [self.listArray addObject:model];
            }
            
        }
        [self.listTable reloadData];
        if(convertToString(dictionary[@"data"][@"page"]).length>0){
            page = [dictionary[@"data"][@"page"] intValue] + 1;
        }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}


-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    if(type == ZZClickOpenVC && [senderObj isKindOfClass:[MWPhotoBrowser class]]){
        MWPhotoBrowser *vc = senderObj;
        startView = vc.startView;
        vc.transitioningDelegate = self;
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }
    
    [ZZCoreTools sucaiListenerImpl:senderObj type:type page:self refresh:_listTable];
}

#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([_entity.nav_name isEqual:@"推荐"] || [_entity.nav_name isEqual:@"关注"]){
        return 0.1f;
    }
    
    return _headerViewLabels.hidden ? 44.0f : (44 + (_headerViewLabels.frame.size.height));
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return _headerView;
}


-(MyButton *) createMenuButton:(CGRect) f m:(NavTypeEntity *)entity{
    MyButton *b = [MyButton buttonWithType:UIButtonTypeCustom];
    b.titleLabel.font = FontFiftent;
    [b setTitleColor:UIColorFromRGB(TextWhiteColor) forState:UIControlStateSelected];
    [b setTitleColor:UIColorFromRGBAlpha(TextWhiteColor, 0.6) forState:UIControlStateNormal];
    [b setFrame:f];
    if(entity){
        [b setTitle:entity.cat_name forState:0];
        b.objTag = entity;
    }
    if([@[@"推荐",@"热门",@"最新"] containsObject:convertToString(entity.nav_name)]){
        [b addTarget:self action:@selector(onItemClick:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [b addTarget:self action:@selector(onItemLabelClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return b;
}

-(void)addBottomItems:(UIView *) sectionView{
    [sectionView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    int i = 1;
    CGFloat sx = 15.0f;
//    NSArray *types = @[@"fav_hot",@"day_hot",@"day_hot",@"recomment"];
    NSArray *types = @[@"recommend", @"week_hot", @"day_new"];
    for(NSString *item in @[@"推荐",@"热门",@"最新"]){
        NavTypeEntity *entity = [NavTypeEntity new];
        entity.nav_id = convertIntToString(i);
        entity.nav_name = item;
        entity.nav_type = types[i-1];
        
        CGRect f = CGRectMake(22 + (i-1)*30 + (i-1)*sx, 0, 30, 44);
        MyButton *btn = [self createMenuButton:f m:entity];
        btn.tag = i;
        [btn setTitle:item forState:0];
        [btn.titleLabel setFont:FontThirteen];
        
        [sectionView addSubview:btn];
        
        if(checkMenuBtn){
            if(checkMenuBtn.tag == btn.tag){
                btn.selected = YES;
            }
        }else{
            if(i == 1){
                btn.selected = YES;
                checkMenuBtn = btn;
            }
        }
        i = i + 1;
    }
    
    
    _btnArrow = [self createButton];
    [_btnArrow setImage:[UIImage imageNamed:@"btn_arrow_down"] forState:0];
    [_btnArrow setImageEdgeInsets:UIEdgeInsetsMake(0, 9, 0, 9)];
    [_btnArrow addTarget:self action:@selector(btnArrowClick:) forControlEvents:UIControlEventTouchUpInside];
    [_btnArrow setFrame:CGRectMake(ScreenWidth - 20 - 44, 0, 44, 44)];
    [sectionView addSubview:_btnArrow];
    
    _headerViewLabels.hidden = YES;
    [_headerView addSubview:_headerViewLabels];
}




// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZHomeListCell *cell = (ZZHomeListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZHomeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell dataToView:[_listArray objectAtIndex:indexPath.row]];
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZZHomeTopicEntity *model=[_listArray objectAtIndex:indexPath.row];
    ZZContentDetailController *vc = [[ZZContentDetailController alloc] init];
    vc.entity = model;
    [self openPushVC:vc];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.section+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint vel = [scrollView.panGestureRecognizer velocityInView:scrollView];
    if(vel.y < 0 && !_headerViewLabels.hidden){
        
        [_btnArrow setImage:[UIImage imageNamed:@"btn_arrow_down"] forState:0];
        _headerViewLabels.hidden = YES;
        [_listTable reloadData];
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//        [_listTable reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
        // 上拉
        if(_labelView){
            [_labelView hideTopTags];
        }
    }
    
    CGPoint offset = scrollView.contentOffset;
    
    if (offset.y < 0) {
        CGFloat delta = 0.0f;
        CGRect rect = self.originFrame;
        delta = fabs(MIN(0.0f, offset.y));
        rect.size.height += delta;
        self.avatarImageView.frame = rect;
        
    }else {
//        CGRect frame = self.avatarImageView.frame;
        self.avatarImageView.frame = self.originFrame;
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}



/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    
    return expectedLabelSize;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//请登录
-(void)showLogin{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:Unlogin_tip message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *login = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoginController *loginVC = [[LoginController alloc] init];
        [self addChildViewController:loginVC];
        [self.navigationController pushViewController:loginVC animated:YES];
    }];
    [alert addAction:cancle];
    [alert addAction:login];
    [self presentViewController:alert animated:YES completion:nil];
}



- (UIImage*)generateImageWithColor:(UIColor*)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}



- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return [self generateAnimatorWithPresenting:YES];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [self generateAnimatorWithPresenting:NO];
}

- (PictureBroswerTransitionAnimator *)animator
{
    if (!_animator) {
        _animator = [[PictureBroswerTransitionAnimator alloc] init];
//        _animator.i
        
    }
    return _animator;
}

- (PictureBroswerTransitionAnimator *)generateAnimatorWithPresenting:(BOOL)presenting {
    PictureBroswerTransitionAnimator *animator = [[PictureBroswerTransitionAnimator alloc] init];
    animator.presenting = presenting;
    
    NSLog(@"startView:%@", NSStringFromCGRect(startView.frame));
    
    if(startView){
        animator.originFrame = [startView.superview convertRect:startView.frame toView:[UIApplication sharedApplication].keyWindow];
    }
    return animator;
}
@end
